//引入工具
import PizZip from "pizzip";
import Docxtemplater from "docxtemplater";
import ImageModule from 'docxtemplater-image-module-free';
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
// 加载 .docx 模板文件
function loadFile(url, callback) {
  JSZipUtils.getBinaryContent(url, callback);
}

// 下载生成的文档
export function download(file, name) {
  saveAs(file, name);
}

const base64DataURLToArrayBuffer = (dataURL) => {
  const base64Regex = /^data:image\/(png|jpg|jpeg|svg|svg\+xml);base64,/;
  if (!base64Regex.test(dataURL)) {
    return false;
  }
  const stringBase64 = dataURL.replace(base64Regex, "");
  let binaryString;
  if (typeof window !== "undefined") {
    binaryString = window.atob(stringBase64);
  } else {
    binaryString = new Buffer(stringBase64, "base64").toString("binary");
  }
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    const ascii = binaryString.charCodeAt(i);
    bytes[i] = ascii;
  }
  return bytes.buffer;
};

// 生成并下载 Word 文档(templatePath是word文档模版地址,data是对应的数据)
export function generateWordDocument(templatePath, data) {

  if(!data)return;

  

  const imageArrayBuffer = base64DataURLToArrayBuffer(data.img1);
  const imageArrayBuffer2 = base64DataURLToArrayBuffer(data.img2);
  const imageArrayBuffer3 = base64DataURLToArrayBuffer(data.img3);
  const imageArrayBuffer4 = base64DataURLToArrayBuffer(data.img4);
  const imageArrayBuffer5 = base64DataURLToArrayBuffer(data.numEnPie);
  const imageArrayBuffer6 = base64DataURLToArrayBuffer(data.numEnLine);
  const imgDataDict = {
    img1: imageArrayBuffer,
    img2: imageArrayBuffer2,
    img3: imageArrayBuffer3,
    img4: imageArrayBuffer4,
    numEnPie: imageArrayBuffer5,
    numEnLine: imageArrayBuffer6,
  };

  console.log(0,imageArrayBuffer)
  return new Promise((resolve, reject) => {
    loadFile(templatePath, function (error, content) {
      if (error) {
        reject(new Error(`Error loading template file: ${error.message}`));
        return;
      }

      try {
        // 加载模板文件内容到 PizZip
        // const docxData =  fetch('/template.docx');
        // const docxArrayBuffer =  content.arrayBuffer();

        const zip = new PizZip(content);
        const doc = new Docxtemplater(zip, {
          paragraphLoop: true,
          linebreaks: true,
          modules: [
            new ImageModule({
              centered:true,
              getImage: (value, key) => {               
                return imgDataDict[key];
              },
              getSize: (afterValue, value, key) => {
                return [500, 300];
              },
            }),
          ],
        });

        // 设置模板中的占位符数据
        doc.setData(data);

        // 渲染文档{xgq: "xgq", // 这里得是字符串否则会报错}
        doc.render();

        // 生成最终的文档 Blob
        const fileWord = doc.getZip().generate({
          type: "blob",
          mimeType:
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        });

        // 返回生成的文档 Blob
        resolve(fileWord);
      } catch (error) {
        console.error("Error rendering document:", error);
        reject(new Error(`Error rendering document: ${error.message}`));
      }
    });
  });
}
